package project.web;

import com.alibaba.fastjson.JSON;
import project.pojo.CourseForSelect;
import project.pojo.CourseTable;
import project.pojo.Student;
import project.service.StudentService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
    StudentService service = new StudentService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        long studentId = Long.parseLong(request.getParameter("studentId"));
        String q = request.getParameter("q");
        if ("studentInfo".equals(q)){
            Student student = service.selectById(studentId);
            String studentInfoJSON = JSON.toJSONString(student);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(studentInfoJSON);
        }else if ("allCourses".equals(q)){
            List<CourseForSelect> courses =  service.showAllCourses(studentId);
            service.setValuesCourses(courses,studentId);
            String coursesJSON = JSON.toJSONString(courses);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(coursesJSON);
        }else if ("allSelected".equals(q)){
            List<CourseForSelect> courses = service.showAllSelected(studentId);
            String coursesJSON = JSON.toJSONString(courses);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(coursesJSON);
        }else if("courseTable".equals(q)){
            List<CourseTable> courseTables = service.showCourseTable(studentId);
            String courseTablesJSON = JSON.toJSONString(courseTables);
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(courseTablesJSON);
        }else if ("select".equals(q)){
            long courseId = Long.parseLong(request.getParameter("courseId"));
            int res = service.insertStudentRecord(courseId, studentId);
            if (res>0){
                response.getWriter().write("success");
            }else{
                response.getWriter().write("fail");
            }
        }else if ("delete".equals(q)){
            long courseId = Long.parseLong(request.getParameter("courseId"));
            int res = service.deleteCourseSelected(courseId, studentId);
            if (res>0){
                response.getWriter().write("success");
            }else{
                response.getWriter().write("fail");
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
